package cn.chint.manage.controller;


import java.io.IOException;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.binarywang.wxpay.bean.entpay.EntPayRequest;
import com.github.binarywang.wxpay.bean.entpay.EntPayResult;
import com.github.binarywang.wxpay.service.EntPayService;
import com.github.binarywang.wxpay.service.WxPayService;

import cn.chint.bo.MsgEnterPages;
import cn.chint.bo.MsgEnterTempbo;
import cn.chint.bo.MsgEnterbo;
import cn.chint.bo.MyLevenshtein;
import cn.chint.manage.dao.MsgenterDao;
import cn.chint.manage.dao.UserDao;
import cn.chint.manage.service.MsgenterService;
import cn.chint.manage.service.UserService;
import cn.chint.po.MsgEnter;
import cn.chint.po.NoticeUser;
import cn.chint.po.Orders;
import cn.chint.po.User;
import cn.chint.servlet.Common;
import cn.chint.util.BeanUtil;
import cn.chint.util.HTTPClientUtils;
import cn.chint.util.PushMsg;
import cn.chint.util.RequestIp;
import cn.chint.util.UtilDate;


@Controller
public class MsgenterController { 


	@Autowired
	MsgenterService msgenterService;
	@Autowired
	MsgenterDao msgenterDao ;

	@SuppressWarnings("unused")
	@Value("${chint.image.url}")
	private String image_url;

	@Value("${chint.image.path}")
	private String image_path;

	@SuppressWarnings("unused")
	@Value("${chint.file.url}")
	private String file_url;

	@SuppressWarnings("unused")
	@Value("${chint.file.path}")
	private String file_path;

	@Autowired
	UserService userService;
	
	@Autowired
	UserDao userDao;

	public Logger log = Logger.getLogger(getClass());

	@RequestMapping(value = "msgUpdate", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public String Update(HttpServletRequest request){
		String money = request.getParameter("money");
		long id = Long.parseLong(request.getParameter("id"));
		log.info(money);
		log.info(id);
		com.alibaba.fastjson.JSONObject o = new com.alibaba.fastjson.JSONObject();
		msgenterService.Update(money, id);
		o.put("status", true);
		o.put("msg", "修改成功");
		return o.toString();//data
	}


	@RequestMapping(value = "msgUpdate2", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public String msgUpdate2(HttpServletRequest request){
		String money = request.getParameter("money");
		long id = Long.parseLong(request.getParameter("id"));
		log.info(money);
		log.info(id);
		msgenterService.Update(money, id);
		
		com.alibaba.fastjson.JSONObject o = new com.alibaba.fastjson.JSONObject();
		o.put("status", true);
		o.put("msg", "提交成功");
		return o.toString();
		
	}
	
	/**匹配项目相似度后，用户确定提交 项目详情信息**/
	@RequestMapping(value = "mes", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public String  mesadd(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response)  {
		com.alibaba.fastjson.JSONObject o = new com.alibaba.fastjson.JSONObject();
		try{
			 String provider_name = request.getParameter("provider_name");
			 String provider_phone_number = request.getParameter("provider_phone_number");
			String provid = request.getParameter("provid");
			String cityid = request.getParameter("cityid");
			String project_start_time = request.getParameter("project_start_time");
			String scale = request.getParameter("scale");
			String customer_type = request.getParameter("customer_type");
			String project_description = request.getParameter("project_description");
			String file_url = request.getParameter("file_url");
			String project_progress = request.getParameter("project_progress");
			String communic = request.getParameter("communic");
			final String openid = request.getParameter("openid");
			String project_name = request.getParameter("project_name");
			String channel = request.getParameter("channel");
			String truth_type = request.getParameter("truth_type");
			String customer_type_product=request.getParameter("customer_type_product");
			String like_name = request.getParameter("like_name");
			String like_value=request.getParameter("like_value");
			String like_v = new BigDecimal(like_value).multiply(new BigDecimal(100)).setScale(1,BigDecimal.ROUND_HALF_UP)+"%"  ;
			final String zf_openid =request.getParameter("zf_openid");
			
			String money = "0";
			switch (scale) {
			case "<500万":
				money = "25";
				break;
			case "500万-1500万":
				money = "50";
				break;
			case "1500万-5000万":
				money = "75";
				break;
			case ">5000万":
				money = "100";
				break;
			}
			String trial="0";
			String review="0";
			//取当前时间
			SimpleDateFormat sf = new SimpleDateFormat("yyyymmdd");
			/***订单号生成规则  ：当前“年月日”  加上   “3位随机数，不足3位补0”  加上 “用户ID唯一” ******/
			log.info(openid);
			List<User> list = userService.getSel(openid);
			User user = list.get(0);
			String OrderNo = sf.format(new Date()) + String.format("%03d",Integer.parseInt(UtilDate.getThree())) +  user.getId();
			/**订单号生成规则  结束**/
			
			final MsgEnter m = new MsgEnter();
			m.setProvider_name(provider_name);
			m.setProvider_phone_number(provider_phone_number);
			m.setProvid(provid);
			m.setCityid(cityid);
			m.setProject_name(project_name);
			m.setProject_start_time(project_start_time);
			m.setScale(scale);
			m.setTruth_type(truth_type);
			m.setCustomer_type(customer_type);
			m.setProject_description(project_description);
			m.setFile_url(file_url);
			m.setTrial(trial);
			m.setReview(review);
			m.setCommunic(communic);
			m.setProject_progress(project_progress);
			m.setCreatetime(new Date());
			m.setOpenid(openid);
			m.setMoney(money);
			m.setOrderNo(OrderNo);
			m.setChannel(channel);
			m.setCustomer_type_product(customer_type_product);
			m.setLike_name(like_name);
			m.setZf_openid(zf_openid);
			m.setLike_value(like_v);
			m.setPseudo(1L);
			
			msgenterService.savemsg(m);
			o.put("status", true);
			o.put("msg", "提交成功");
			Common.ls.add(project_name);
			
			
			//List<User> list = userService.getSel(openid);
			//User user = list.get(0);
			String first_value="用户提交了项目申请，请即时确认";
			final String keyword1_value=provider_name;//用户姓名
			final String keyword2_value=provider_phone_number;//用户手机
			final String keyword3_value =UtilDate.getTime(new Date()) ;  //提交时间
			String keyword4_value ="点击查看项目详情，或登录后台系统查看。";
			String redic_url = "http://lead.taiwuyou.cn/chint-dl/mobile/msgdetail.html?id="+m.getId(); //跳转地址 
			/***通知运营人员*****/
			String type="1";//
			NoticeUser   u = msgenterDao.findNoticeUser(type);//查询运营人员的openid  
			PushMsg.submit_push_msg(u.getOpenid(),first_value,keyword1_value,keyword2_value,keyword3_value,keyword4_value,redic_url);//消息模板推送
			
			/****通知提交用户。线程异步2分钟执行。等待用户提交后关注微信公众号 二维码后 ，再发通知。不然未关注的用户收不到服务通知。*******/
			ExecutorService  pool = Executors.newCachedThreadPool();
			pool.execute(new Runnable() {  
				public void run() {  
	            	try {
	            		if(!"".equals(zf_openid) && zf_openid !=null){
		            		Thread.sleep(1000*35);
		            	}
	            		final String first_value="提交项目申请，请耐心等待审核结果";
	        			final String keyword4_value ="点击查看项目详情";
	        			final String id =m.getId().toString();
	        			final String redic_url = "http://lead.taiwuyou.cn/chint-dl/mobile/msgdetail_user.html?id="+id;; //跳转地址 
	        			/***通知提交人员*****/
	        			PushMsg.submit_push_msg(openid,first_value,keyword1_value,keyword2_value,keyword3_value,keyword4_value,redic_url);//消息模板推送
					} catch (Exception e) {
						e.printStackTrace();
					}
	            }  
	        });
			pool.shutdown();
			
			return o.toString();//data

		}catch (Throwable e) {
			e.printStackTrace();
			log.info("错误信息"+e.getMessage());
			o.put("status", false);
			o.put("msg", "提交失败");
			return o.toString();
		}
	}
/**添加项目详情信息**/
	@RequestMapping(value = "msgenter", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public String  msgadd(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response)  {
		com.alibaba.fastjson.JSONObject o = new com.alibaba.fastjson.JSONObject();

		try{
			//	String json = 	request.getParameter("s_form_data");
			//	log.info(json);
			//	com.alibaba.fastjson.JSONObject jb = com.alibaba.fastjson.JSONObject.parseObject(json);	
			String provider_name = request.getParameter("provider_name");
			String provider_phone_number = request.getParameter("provider_phone_number");
			String provid = request.getParameter("provid");
			String cityid = request.getParameter("cityid");
			String project_start_time = request.getParameter("project_start_time");
			String scale = request.getParameter("scale");
			String customer_type = request.getParameter("customer_type");
			String project_description = request.getParameter("project_description");
			String file_url = request.getParameter("file_url");
			String project_progress = request.getParameter("project_progress");
			String communic = request.getParameter("communic");
			final String openid = request.getParameter("openid");
			String project_name = request.getParameter("project_name");
			String truth_type = request.getParameter("truth_type");
			String channel = request.getParameter("channel");
			String customer_type_product=request.getParameter("customer_type_product");
			final String zf_openid =request.getParameter("zf_openid");
			String money = "0";
			switch (scale) {
			case "<500万":
				money = "25";
				break;
			case "500万-1500万":
				money = "50";
				break;
			case "1500万-5000万":
				money = "75";
				break;
			case ">5000万":
				money = "100";
				break;
			}
			
			/**验证数据库中项目的相似度**/
			//List<MsgEnter> ls = msgenterService.Select(provid, cityid);
			List<String> ls = Common.ls;/***获取缓存集合中所有的项目名称***/
			log.info(ls.size()); 
			//String name =null;
			float min = 0;
			for (String name : ls) {
					//name = msgEnter.getProject_name();
					min = MyLevenshtein.levenshtein(name, project_name);
					log.info("相似值:"+min);
					if(min >= 0.7){
						o.put("status", "2");
						o.put("msg", "这个项目已存在，提交失败。");
						return o.toString();//data
					}
			}
			for (String name : ls) {
				    //name = msgEnter.getProject_name();
				    min = MyLevenshtein.levenshtein(name, project_name);
				    if (min < 0.7 && min >=0.5) {
				    o.put("status", "1");
					o.put("like_value", min);
					o.put("like_name", name);
					
					return o.toString();//data
				}
		}
			
			String trial="0";
			String review="0";
			//取当前时间
			SimpleDateFormat sf = new SimpleDateFormat("yyyymmdd");
			/***订单号生成规则  ：当前“年月日”  加上   “3位随机数，不足3位补0”  加上 “用户ID唯一” ******/
			log.info(openid);
			List<User> list = userService.getSel(openid);
			User user = list.get(0);
			String OrderNo = sf.format(new Date()) + String.format("%03d",Integer.parseInt(UtilDate.getThree())) +  user.getId();
			/**订单号生成规则  结束**/
			
			final MsgEnter m = new MsgEnter();
			m.setProvider_name(provider_name);
			m.setProvider_phone_number(provider_phone_number);
			m.setProvid(provid);
			m.setCityid(cityid);
			m.setProject_start_time(project_start_time);
			m.setScale(scale);
			m.setTruth_type(truth_type);
			m.setCustomer_type(customer_type);
			m.setProject_description(project_description);
			m.setFile_url(file_url);
			m.setTrial(trial);
			m.setReview(review);
			m.setCommunic(communic);
			m.setProject_progress(project_progress);
			m.setCreatetime(new Date());
			m.setOpenid(openid);
			m.setProject_name(project_name);
			m.setMoney(money);
			m.setOrderNo(OrderNo);
			m.setChannel(channel);
			m.setCustomer_type_product(customer_type_product);
			m.setPseudo(1L);
			m.setZf_openid(zf_openid);
			
			msgenterService.savemsg(m);/*****保存到数据库中，并添加到缓存集合中*************/
			o.put("status", "0");
			o.put("msg", "提交成功");
			Common.ls.add(project_name);
			
			//List<User> list = userService.getSel(openid);
			//User user = list.get(0);
			String first_value="用户提交了项目申请，请即时确认";
			final String keyword1_value=provider_name;//用户姓名
			final String keyword2_value=provider_phone_number;//用户手机
			final String keyword3_value =UtilDate.getTime(new Date()) ;  //提交时间
			String keyword4_value ="点击查看项目详情，或登录后台系统查看。";
			String redic_url = "http://lead.taiwuyou.cn/chint-dl/mobile/msgdetail.html?id="+m.getId(); //跳转地址 
			/***通知运营人员*****/
			String type="1";//
			NoticeUser   u = msgenterDao.findNoticeUser(type);//查询运营人员的openid  
			PushMsg.submit_push_msg(u.getOpenid(),first_value,keyword1_value,keyword2_value,keyword3_value,keyword4_value,redic_url);//消息模板推送
			
			/****通知提交用户。线程异步2分钟执行。等待用户提交后关注微信公众号 二维码后 ，再发通知。不然未关注的用户收不到服务通知。*******/
			ExecutorService  pool = Executors.newCachedThreadPool();
			pool.execute(new Runnable() {  
				public void run() {  
	            	try {
	            		if(!"".equals(zf_openid) && zf_openid !=null){
	            		Thread.sleep(1000*35);
	            		}
	            		final String first_value="提交项目申请，请耐心等待审核结果";
	        			final String keyword4_value ="点击查看项目详情";
	        			final String id =m.getId().toString();
	        			final String redic_url = "http://lead.taiwuyou.cn/chint-dl/mobile/msgdetail_user.html?id="+id;; //跳转地址 
	        			/***通知提交人员*****/
	        			PushMsg.submit_push_msg(openid,first_value,keyword1_value,keyword2_value,keyword3_value,keyword4_value,redic_url);//消息模板推送
					} catch (Exception e) {
						e.printStackTrace();
					}
	            }  
	        });
			pool.shutdown();
			
			return o.toString();//data

		}catch (Throwable e) {
			e.printStackTrace();
			log.info("错误信息"+e.getMessage());
			o.put("status", "-1");
			o.put("msg", "提交失败");
			return o.toString();
		}
	}


	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "find_msg_enter", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public Map  find_msg_enter(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {

		
		String page = request.getParameter("page");
		String size = request.getParameter("size");
		log.info(page);
		log.info(size);

		MsgEnterPages msgEnterPages =msgenterDao.find_msg_enter(Integer.parseInt(page),Integer.parseInt(size));

		List<MsgEnterTempbo>  ls  = msgEnterPages.getLs();
		
		List<MsgEnterTempbo> list = new ArrayList();

		for(MsgEnterTempbo m:ls){
		
			MsgEnterTempbo MsgEnterTempbo = new MsgEnterTempbo();
			BeanUtils.copyProperties(m, MsgEnterTempbo);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			MsgEnterTempbo.setCreateTime(UtilDate.getTime(sdf.parse(m.getCreateTime())));
			list.add(MsgEnterTempbo);
		}

		// JSONArray json =JSONArray.fromObject(list);
		@SuppressWarnings("rawtypes")
		Map<String, Object> r = new HashMap();
		r.put("code", 0);
		r.put("msg", "");
		r.put("count", msgEnterPages.getMsgenter_num());
		r.put("data", list);

		return r ;
	}
	//后台模糊查询
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value = "find_msg_enter_by_name", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public Map  find_msg_enter_by_name(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException {

		String channelUser=request.getParameter("channelUser");
		String page = request.getParameter("page");
		String size = request.getParameter("size");
		log.info(page);
		log.info(size);
		log.info(channelUser);
		MsgEnterPages msgEnterPages =msgenterDao.find_msg_enter_by_name(Integer.parseInt(page),Integer.parseInt(size),channelUser);

		List<MsgEnterTempbo>  ls  = msgEnterPages.getLs();
		
		List<MsgEnterTempbo> list = new ArrayList();

		for(MsgEnterTempbo m:ls){
		
			MsgEnterTempbo MsgEnterTempbo = new MsgEnterTempbo();
			BeanUtils.copyProperties(m, MsgEnterTempbo);
			 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
			MsgEnterTempbo.setCreateTime(UtilDate.getTime(sdf.parse(m.getCreateTime())));
			list.add(MsgEnterTempbo);
		}

		@SuppressWarnings("rawtypes")
		Map<String, Object> r = new HashMap();
		r.put("code", 0);
		r.put("msg", "");
		r.put("count", msgEnterPages.getMsgenter_num());
		r.put("data", list);

		return r ;
	}
	//msgdetail查询数据****
		@RequestMapping(value = "find_msgdetail", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
		@ResponseBody
		public String  find_msgdetail(ModelMap modelMap,HttpServletRequest request, HttpServletResponse response)  {
			com.alibaba.fastjson.JSONObject o = new com.alibaba.fastjson.JSONObject();
				//Long id=Long.parseLong(request.getParameter("id"));
				Long id=Long.parseLong(request.getParameter("id"));
				MsgEnterTempbo  msgEnter = msgenterDao.getMsgEnter(id);
				/*modelMap.addAttribute("Customer_type",msgEnter.getCustomer_type());*/
				log.info(modelMap);
				o.put("msgEnter", msgEnter);
				o.put("status", true);
				return o.toJSONString();

		}

	
	/**初审   初审通过 通知复审人员***/
	@RequestMapping(value = "comfire_trial", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public String  trial_upload(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response)  {
		com.alibaba.fastjson.JSONObject o = new com.alibaba.fastjson.JSONObject();

		try{
			Long id=Long.parseLong(request.getParameter("id"));
			String trial="1"; //0:待审核    1：初审通过
			//		MsgEnter m =msgenterDao.updaterial(id, trial);
			msgenterDao.updatetrial(id, trial);

			o.put("status", true);
			o.put("msg", "通过初审");
			
			String first_value="用户提交了项目申请，请即时确认";
			MsgEnterTempbo   msgEnter = msgenterDao.getMsgEnter(id);
			String keyword1_value=msgEnter.getProvider_name();//用户姓名
			String keyword2_value=msgEnter.getProvider_phone_number();//用户手机
			String keyword3_value =UtilDate.getTime(new Date()) ;  //提交时间
			String keyword4_value ="点击查看项目详情，或登录后台系统查看。";
			
			String redic_url = "http://lead.taiwuyou.cn/chint-dl/mobile/msgdetail2.html?id="+id; //跳转地址 
			
			/***通知复审运营人员*****/
			String type="2";//
			NoticeUser   u = msgenterDao.findNoticeUser(type);//查询运营人员的openid  
			PushMsg.submit_push_msg(u.getOpenid(),first_value,keyword1_value,keyword2_value,keyword3_value,keyword4_value,redic_url);//消息模板推送
			
			
			return o.toString();//data

		}catch (Throwable e) {
			e.printStackTrace();
			log.info("错误信息"+e.getMessage());
			o.put("status", false);
			o.put("msg", "提交失败");
			return o.toString();
		}
	}

	//复审
	@RequestMapping(value = "comfire_review", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public String  review_upload(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response)  {
		com.alibaba.fastjson.JSONObject o = new com.alibaba.fastjson.JSONObject();

		try{
			Long id=Long.parseLong(request.getParameter("id"));
			String review="1"; //0:待初审通过    1：复审通过
			//		MsgEnter m =msgenterDao.updaterial(id, trial);
			msgenterDao.updatereview(id, review);

			MsgEnterTempbo  msgEnter = msgenterDao.getMsgEnter(id);
			log.info("Openid"+msgEnter.getOpenid());
			log.info("Project_start_time"+msgEnter.getProject_start_time());
			
			/***订单号生成规则  ：当前“年月日”  加上   “3位随机数，不足3位补0”  加上 “用户ID唯一”
			/***调用微信企业到零钱的 API接口****/
			List<User> list = userService.getSel(msgEnter.getOpenid());
			User u = list.get(0);
			SimpleDateFormat sf = new SimpleDateFormat("yyyymmdd");
			String OrderNo = sf.format(new Date()) + String.format("%03d",Integer.parseInt(UtilDate.getThree())) +  u.getId();
			try{
				//成功会返回   微信付款单号，不成功会抛出异常。
			   String paymentNo = userWithgraw(msgEnter.getOpenid(), RequestIp.getIPAddress(request), msgEnter.getMoney(), OrderNo);/***调用微信企业到零钱的 API接口****/
			   /**订单号生成规则  结束,保存订单**/
				Orders openid_order = new Orders();
				openid_order.setAmount(new BigDecimal(msgEnter.getMoney()));
				openid_order.setCreatetime(new Date());
				openid_order.setProject_id(id);
				openid_order.setProject_name(msgEnter.getProject_name());
				openid_order.setMsg("项目通过，奖励提交者的红包");
				openid_order.setOpenid(msgEnter.getOpenid());
				openid_order.setOrder_status(2);//下发成功
				openid_order.setType("1");
				openid_order.setOrderNo(OrderNo);//用户订单号
				openid_order.setPaymentNo(paymentNo);//微信付款单号
				userService.saveOrder(openid_order);
			}catch(Exception e){
				log.info(e.getMessage());
				Orders openid_order = new Orders();
				openid_order.setAmount(new BigDecimal(msgEnter.getMoney()));
				openid_order.setCreatetime(new Date());
				openid_order.setProject_id(id);
				openid_order.setProject_name(msgEnter.getProject_name());
				openid_order.setMsg("项目通过，奖励提交者的红包");
				openid_order.setDescribe_info(e.getMessage());
				openid_order.setOpenid(msgEnter.getOpenid());
				openid_order.setOrder_status(-1);//下发失败
				openid_order.setType("1");
				openid_order.setOrderNo(OrderNo);//用户订单号
				userService.saveOrder(openid_order);
				o.put("status", true);
				o.put("msg", e.getMessage());
				return o.toString();
			}
			/**通知提交用户**/
			String time = UtilDate.getFormateDate(new Date());
			String first_value="尊敬的用户您好！您提供的项目'"+msgEnter.getProject_name()+"'已被公司采纳，奖励金额："+msgEnter.getMoney()+"元。"; 
			//String keyword1_value="您提供的订单号:"+msgEnter.getOrderNo()+  "，项目名称：'"+msgEnter.getProject_name()+"'被采纳，奖励红包金额："+msgEnter.getMoney()+"元"+"。点击添加客服领取奖励。";  //完成情况
			String keyword1_value="已通过审核。";
			String keyword2_value =UtilDate.getTime(new Date()) ; 
			//String remark_value="订单号是："+msgEnter.getOrderNo() +"。请点击查看合约并添加客服领取奖励。";   //备注说明   订单号
			String remark_value="订单号是："+msgEnter.getOrderNo() +"请查收奖励。";   //备注说明   订单号
			String redic_url = "http://lead.taiwuyou.cn/chint-dl/mobile/contract.html?orderno="+msgEnter.getOrderNo()+"&phone="+msgEnter.getProvider_phone_number()+"&time="+time; //跳转地址 
			PushMsg.push_msg(msgEnter.getOpenid(),first_value,keyword1_value,keyword2_value,remark_value,redic_url);/**消息模板推送*/
			
			/**通知转发用户**/
			String zf_openid = msgEnter.getZf_openid();/**转发用户openid**/
			if(!"".equals(zf_openid) && zf_openid !=null){
				/***订单号生成规则  ：当前“年月日”  加上   “3位随机数，不足3位补0”  加上 “用户ID唯一”
				/***调用微信企业到零钱的 API接口****/
				List<User> list2 = userService.getSel(zf_openid);
				User u2 = list2.get(0);
				SimpleDateFormat sf2 = new SimpleDateFormat("yyyymmdd");
				String OrderNo2 = sf2.format(new Date()) + String.format("%03d",Integer.parseInt(UtilDate.getThree())) +  u2.getId();
				try{
					//成功会返回   微信付款单号，不成功会抛出异常。
				   String paymentNo = userWithgraw(msgEnter.getOpenid(), RequestIp.getIPAddress(request), msgEnter.getMoney(), OrderNo2);/***调用微信企业到零钱的 API接口****/
				   /**订单号生成规则  结束,保存订单**/
					Orders zf_openid_order = new Orders();
					zf_openid_order.setAmount(new BigDecimal("0.4"));//转发用户0.4元
					zf_openid_order.setCreatetime(new Date());
					zf_openid_order.setProject_id(id);
					zf_openid_order.setProject_name(msgEnter.getProject_name());
					zf_openid_order.setMsg("项目通过，奖励转发者的红包");
					zf_openid_order.setOpenid(zf_openid);
					zf_openid_order.setOrder_status(2);//下发成功
					zf_openid_order.setType("1");
					zf_openid_order.setOrderNo(OrderNo2);//用户订单号
					zf_openid_order.setPaymentNo(paymentNo);//微信付款单号
					userService.saveOrder(zf_openid_order);
				}catch(Exception e){
					log.info(e.getMessage());
					Orders zf_openid_order = new Orders();
					zf_openid_order.setAmount(new BigDecimal("0.4"));//转发用户0.4元
					zf_openid_order.setCreatetime(new Date());
					zf_openid_order.setProject_id(id);
					zf_openid_order.setProject_name(msgEnter.getProject_name());
					zf_openid_order.setMsg("项目通过，奖励转发者的红包");
					zf_openid_order.setDescribe_info(e.getMessage());
					zf_openid_order.setOpenid(zf_openid);
					zf_openid_order.setOrder_status(-1);//下发失败
					zf_openid_order.setType("1");
					zf_openid_order.setOrderNo(OrderNo2);//用户订单号
					userService.saveOrder(zf_openid_order);
					userService.saveOrder(zf_openid_order);
					o.put("status", true);
					o.put("msg","‘下发提交用户奖励成功。但是下发转发用户奖励红白失败’：："+ e.getMessage());
					return o.toString();
				}
				
				String openid = msgEnter.getOpenid();      /***提交用户openid***/
				List<User> ll =  userDao.getSel(openid);
				User user = ll.get(0);
				/**通知转发用户**/
				String first_value2="尊敬的客户！您的粉丝 '"+user.getWx_nickname()+"' 提交的项目已通过审核。"; 
				//String keyword1_value="您提供的订单号:"+msgEnter.getOrderNo()+  "，项目名称：'"+msgEnter.getProject_name()+"'被采纳，奖励红包金额："+msgEnter.getMoney()+"元"+"。点击添加客服领取奖励。";  //完成情况
				String keyword1_value2="已通过审核。";
				String keyword2_value2 =UtilDate.getTime(new Date()) ; 
//				String remark_value2="请点击后扫描二维码添加客服微信领取奖励";   //备注说明   订单号
				String remark_value2="请查收奖励";   //备注说明   订单号
				String redic_url2 = "http://lead.taiwuyou.cn/chint-dl/mobile/cus_service.jpg"; //跳转地址 
				PushMsg.push_msg(zf_openid,first_value2,keyword1_value2,keyword2_value2,remark_value2,redic_url2);/**消息模板推送*/
			}

			o.put("status", true);
			o.put("msg", "通过审核");
			return o.toString();//data

		}catch (Throwable e) {
			e.printStackTrace();
			log.info("错误信息"+e.getMessage());
			o.put("status", false);
			o.put("msg", "提交失败");
			return o.toString();
		}
	}
	
	//拒绝通过
	@RequestMapping(value = "reject_pass", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public String  reject_pass(ModelMap modelMap, HttpServletRequest request, HttpServletResponse response)  {
		com.alibaba.fastjson.JSONObject o = new com.alibaba.fastjson.JSONObject();

		try{
			
			String s_form_data = request.getParameter("s_form_data");
			com.alibaba.fastjson.JSONObject  jsonObject = com.alibaba.fastjson.JSONObject.parseObject(s_form_data);
			String reject_reason = jsonObject.getString("reject_reason");
			long id = jsonObject.getLong("id");
			
			log.info(s_form_data);
			
			String review="-1"; //0:待初审通过    1：复审通过   -1拒绝
			msgenterDao.reject_pass(id, reject_reason,review);
			
			
			MsgEnterTempbo  msgEnter = msgenterDao.getMsgEnter(id);
			log.info("Openid"+msgEnter.getOpenid());
			log.info("Project_start_time"+msgEnter.getProject_start_time());

			/**通知用户**/
			String first_value="尊敬的用户您好！非常抱歉您提供的项目'"+msgEnter.getProject_name()+"'未通过公司审核。"; 
			String keyword1_value=UtilDate.getTime(new Date()) ;  //完成日期
			String keyword2_value =msgEnter.getReject_reason();//拒绝理由
			String remark_value="正泰电力服务有限公司期待您再次踊跃参与";   //备注说明
			String redic_url = null; //跳转地址 
			PushMsg.push_msg_result(msgEnter.getOpenid(),first_value,keyword1_value,keyword2_value,remark_value,redic_url);/**消息模板推送*/


			o.put("status", true);
			o.put("msg", "拒绝成功");
			return o.toString();//data

		}catch (Throwable e) {
			e.printStackTrace();
			log.info("错误信息"+e.getMessage());
			o.put("status", false);
			o.put("msg", "提交失败");
			return o.toString();
		}
	}
	


    @RequestMapping(value = "pseudo", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	@ResponseBody
	public String UpdPseudo(HttpServletRequest request){
    	
    	com.alibaba.fastjson.JSONObject o = new com.alibaba.fastjson.JSONObject();
		long id = Long.parseLong(request.getParameter("id"));
		long pseudo = 0;
		msgenterDao.UpdPseudo(id, pseudo);
		o.put("status", true);
		o.put("msg", "删除成功");
		return o.toString();//data
	}
    
    
    
	@Autowired
    WxPayService wxPayService;
	public String  userWithgraw(String openid,String ipAddress,String money,String orderNo)  throws Exception{
		try{
			
			EntPayService entPayService = wxPayService.getEntPayService();
			EntPayRequest req = new EntPayRequest();
			req.setPartnerTradeNo(orderNo);
			req.setOpenid(openid);
			req.setCheckName("NO_CHECK");
			req.setAmount(new BigDecimal(money).multiply(new BigDecimal("100")).intValue());
			req.setDescription("企业付款");
			//String ipAddress = RequestIp.getIPAddress(request);
			req.setSpbillCreateIp(ipAddress);
			EntPayResult entPayResult =null;
			try{
		        entPayResult = entPayService.entPay(req);
		        log.info("返回消息：  错误码 "+ entPayResult.getErrCode() +"， 错误消息  "+ entPayResult.getErrCodeDes());
		        
		        return entPayResult.getPaymentNo();//微信付款单号
	
//		        if (BeanUtil.isEmpty(entPayResult.getPaymentNo())) {///微信付款单号
//		            log.info(String.format("订单号： %s 企业付款失败")); ///
//		            //throw new GeneralException("081", "企业付款失败");
//		        	return "付款失败";
//		        }
			
			}catch(Exception e){
				//log.info("付款错误返回信息："+e.getMessage());
				//log.info("返回错误码 "+ entPayResult.getErrCode() +" 错误消息  "+ entPayResult.getErrCodeDes());
				//return e.getMessage();
				throw e;
			}
	        
		}catch (Exception e1) {
			//e.printStackTrace();
			//log.info("错误信息"+e.getMessage());
			//return e.getMessage();
			throw e1;
		}
	}
	
}





